<template>
  <div class="alphabet-list">
    <div class="item" v-for="item in letters" :key="item"
         @click="handleClick"
         @touchstart="handleTouchStart"
         @touchmove="handleTouchMove"
         @touchend ="handleTouchEnd"
         :ref="item"
    >
      {{item}}
    </div>
  </div>
</template>
<script>
export default {
  name: 'Alphabet',
  props: {
    cities: Object
  },
  data: function () {
    return {
      lettersArr: [],
      touchFlag: false,
      timer: null,
      startY: 0
    }
  },
  updated: function () {
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    handleClick: function (e) {
      var currentLetter = e.target.innerText
      this.$emit('letterChange', currentLetter)
    },
    handleTouchStart: function () {
      this.touchFlag = true
    },
    handleTouchMove: function (e) {
      if (this.touchFlag) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          const touchY = e.touches[0].clientY
          var letterIndex = Math.floor((touchY - 78 - this.startY) / 20)
          if (letterIndex >= 0 && letterIndex < this.letters.length) {
            this.$emit('letterChange', this.letters[letterIndex])
          }
        }, 16)
      }
    },
    handleTouchEnd: function () {
      this.touchFlag = false
    }
  },
  computed: {
    letters () {
      const letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  }
}
</script>
<style lang="stylus" scoped>
  @import "~stylus/varibles.styl"
  .alphabet-list
    width .35rem
    position absolute
    top 1.58rem
    right 0rem
    bottom 0rem
    display flex
    flex-direction column
    justify-content center
    .item
      height .4rem
      line-height .4rem
      color $bgColor
      font-size .2rem
      text-align center
</style>
